
//
//  ViewController.swift
//  ReplayKitDemo
//
//  Created by Wei Zhang on 2022/2/10.
//

import UIKit
import ReplayKit
import AVKit
class ViewController: UIViewController, RPBroadcastActivityViewControllerDelegate {
    var urls : [URL] = []
    var tableView : UITableView!
    
    func broadcastActivityViewController(_ broadcastActivityViewController: RPBroadcastActivityViewController, didFinishWith broadcastController: RPBroadcastController?, error: Error?) {
        broadcastActivityViewController.dismiss(animated: true, completion: nil)
        if error != nil{
            print("\(error?.localizedDescription ?? "")")
            return
        }else{
            broadcastController?.startBroadcast(handler: { error in
                if error == nil{
                    print("success")
                }else{
                    print("\(error?.localizedDescription ?? "")")
                }
            })
        }
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        let pickerView = RPSystemBroadcastPickerView.init(frame: CGRect.init(x: self.view.bounds.width / 2 - 50, y: 100, width: 100, height: 100))
        pickerView.preferredExtension = "zw.ReplayKitDemo.Upload"
        self.view.addSubview(pickerView)
        
        tableView = UITableView.init(frame: CGRect.init(x: 0, y: 300, width: self.view.bounds.width, height: self.view.bounds.height - 300))
        self.view.addSubview(tableView)
        tableView.delegate = self
        tableView.dataSource = self
    }
    
    @IBAction func replayBtnClicked(_ sender : UIButton){
        //        RPBroadcastActivityViewController.load(withPreferredExtension: "zw.ReplayKitDemo.UploadSetupUI") { broadcastActivityViewController, error in
        //            if error == nil{
        //                broadcastActivityViewController?.delegate = self
        //                broadcastActivityViewController?.modalPresentationStyle = .popover
        //                self.present(broadcastActivityViewController!, animated: true, completion: nil)
        //            }else{
        //                print("\(error?.localizedDescription ?? "")")
        //            }
        //        }
        let documentsDirectory = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.zw.app")
        let replayPath = documentsDirectory?.appendingPathComponent("ShareGroup")
        
        if replayPath != nil{
            let directoryContents = try! FileManager.default.contentsOfDirectory(at: replayPath!, includingPropertiesForKeys: nil, options: [])
            urls = directoryContents
        }else{
            urls = []
        }
        self.tableView.reloadData()
    }
}

extension ViewController : UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return urls.count
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let url = urls[indexPath.row]
        
        let cell = UITableViewCell.init(style: .default, reuseIdentifier: "cell")
        if let name = url.relativePath.split(separator: "/").last{
            cell.textLabel?.text = String(name)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let url = urls[indexPath.row]
        let player = AVPlayerViewController()
        let playerItem = AVPlayerItem.init(url: url)
        player.player = AVPlayer.init(playerItem: playerItem)
        player.videoGravity = .resizeAspectFill
        self.present(player, animated: true, completion: nil)
    }
}
